package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * RPC client
 * 1. 发送请求
 * 2. 接收响应
 */
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        // 2.开启信道
        Channel channel = connection.createChannel();
        // 3.使用内置交换机
        // 4.声明队列
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);
        // 5.发送请求
        String msg = "hello rpc...";
        // 设置请求的唯一标识
        String correlationID = UUID.randomUUID().toString();
        // 设置请求的相关属性
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .correlationId(correlationID)
                .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes());

        // 5.接收响应
        // 使用阻塞队列来存储响应信息
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String resMeg = new String(body);
                System.out.println("接收到回调消息：" + resMeg);
                if (correlationID.equals(properties.getCorrelationId())) {
                    // 如果两个correlationID相等，就表示是该请求返回的响应
                    response.offer(resMeg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result = response.take();
        System.out.println("[RPC Client 响应结果]" + result);
    }
}
